package org.vnl.platform.spring.mvc;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.vnl.platform.orm.IPersistenceManager;
import org.vnl.platform.orm.PersistenceManagerFactory;
import org.vnl.platform.orm.TransactionException;


/**
 * 如果只單用Spring MVC可以利用此一Interceptor來做PDK的transaction control,在spring的設定檔裡設定
 * mvc:interceptors,傳入model and veiw 要回傳的viewName作為errorName的值
 *
 * @author Vaughan
 *
 */
public class TransactionInterceptor implements HandlerInterceptor {

    private static final Logger logger = Logger.getLogger(TransactionInterceptor.class);
    
    private String errorName;
    
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        try {
            IPersistenceManager pm = PersistenceManagerFactory.getInstance().getCurrentPM();
            if (pm.isRollbackOnly()) {
                pm.rollback();
            } else {
                pm.commit();
            }
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        try {
            PersistenceManagerFactory.getInstance().getCurrentPM().begin();
        } catch (TransactionException e) {
            logger.fatal("cannot start transaction",e);
        }
        return true;
    }

    public String getErrorName() {
        return errorName;
    }

    public void setErrorName(String errorName) {
        this.errorName = errorName;
    }

}
